import { useTableScroll } from '@/hooks/useTableScroll';
import { unSignAccount } from '@/services/account-center';
import {
  aliPayEnterpriseAuthentication,
  getTallyBookAccountList,
} from '@/services/financial-center';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Button, Form, Input, Modal, Popconfirm, message } from 'antd';
import { useRef, useState } from 'react';

const ACSPage = () => {
  const [count] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);
  const actionRef = useRef<ActionType>();
  const [openModal, setOpenModal] = useState(false);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [unSignLoading, setUnSignLoading] = useState(false);
  const [unSignItem, setUnSignItem] = useState<{ id?: any }>({});
  const [form] = Form.useForm();
  const [selectedItem, setSelectedItem] = useState<any>({});

  const columns: ProColumns<any>[] = [
    {
      title: '签约时间',
      dataIndex: 'createTime',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '企业名称',
      dataIndex: 'alipayName',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '支付宝账号',
      dataIndex: 'alipayNickName',
      width: 180,
      order: 1,
    },
    {
      title: '记账本账号',
      dataIndex: 'bookId',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '当日转账金额',
      dataIndex: 'currentDayTransLimit',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '本月转账金额',
      dataIndex: 'currentMonthTransLimit',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '备付金余额',
      dataIndex: 'bookBalance',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '签约状态',
      dataIndex: 'signStatus',
      width: 160,
      order: 3,
      valueType: 'select',
      fieldProps: {
        defaultValue: '',
      },
      valueEnum: {
        '': { text: '不限' },
        TEMP: { text: '签约中' },
        STOP: { text: '已解约' },
        NORMAL: { text: '已签约' },
      },
      render: (_, record) => {
        const obj = {
          TEMP: { text: '签约中' },
          STOP: { text: '已解约' },
          NORMAL: { text: '已签约', className: 'text-[#67c23a]' },
        } as any;
        return (
          <div {...obj[record.signStatus]}>{obj[record.signStatus].text}</div>
        );
      },
    },
    {
      title: '企业认证状态',
      dataIndex: 'auditStatus',
      width: 160,
      order: 2,
      valueType: 'select',
      valueEnum: {
        '': { text: '不限' },
        init: { text: '待实名' },
        auditing: { text: '实名审核中' },
        fail: { text: '认证失败' },
        normal: { text: '已认证' },
      },
      fieldProps: {
        defaultValue: '',
      },
      render: (_, record) => {
        const obj = {
          init: { text: '待实名' },
          auditing: { text: '实名审核中' },
          fail: { text: '认证失败' },
          normal: { text: '已认证', className: 'text-[#67c23a]' },
        } as any;
        return (
          <div {...obj[record.auditStatus]}>{obj[record.auditStatus].text}</div>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: '',
      hideInSearch: true,
      fixed: 'right',
      render: (_, record) => {
        return (
          <div className="flex gap-3">
            <span
              className={`${
                !['fail', 'normal'].includes(record.auditStatus) &&
                record.signStatus === 'NORMAL'
                  ? ''
                  : 'hidden'
              } text-[#00bdff] cursor-pointer`}
              onClick={() => {
                history.push(
                  `/account-center/sign-manager/authentication-center?alipayNickName=${record.alipayNickName}`,
                );
              }}
            >
              企业认证
            </span>
            <span
              className={`${
                ['TEMP', 'STOP'].includes(record.signStatus) ? '' : 'hidden'
              } ${
                loading && record.id === selectedItem.id
                  ? 'text-[#e8e8e8]'
                  : 'text-[#00bdff]'
              } cursor-pointer`}
              onClick={() => {
                if (loading) return;
                if (!record.alipayName) {
                  setOpenModal(true);
                  return;
                }
                setSelectedItem(record);
                setLoading(true);
                aliPayEnterpriseAuthentication({
                  alipayName: record.alipayName,
                  alipayNickName: record.alipayNickName,
                })
                  .then((res: any) => {
                    if (res.success) {
                      window.open(res.data);
                    } else {
                      message.error(res.resultMessage);
                    }
                  })
                  .finally(() => {
                    setLoading(false);
                  });
              }}
            >
              重新签约
            </span>
            <Popconfirm
              title="提示"
              description="是否要解约该企业支付宝账号?"
              okButtonProps={{
                loading: unSignLoading,
              }}
              onCancel={() => {
                setUnSignItem({});
              }}
              open={record.id === unSignItem.id}
              onConfirm={() => {
                setUnSignLoading(true);
                unSignAccount({ id: record.id })
                  .then((res: any) => {
                    if (res.success) {
                      message.success('解约成功');
                      actionRef.current?.reload();
                      setUnSignLoading(false);
                      setUnSignItem({});
                    } else {
                      message.error(res.resultMessage);
                    }
                  })
                  .finally(() => {
                    setUnSignLoading(false);
                  });
              }}
              className={`${record.signStatus === 'NORMAL' ? '' : 'hidden'}`}
            >
              <span
                className="text-[#00bdff] cursor-pointer"
                onClick={() => {
                  setUnSignItem(record);
                }}
              >
                解约
              </span>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <ProTable
        scroll={{ y: tableScrollHeight, x: 200 }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        request={async (params: any) => {
          const { current, ...rest } = params;
          const searchData = {
            pageNo: current - 1,
            ...rest,
          };
          try {
            const { data, count, success } = (await getTallyBookAccountList(
              searchData,
            )) as any;
            if (success) {
              return {
                data,
                total: count,
                success,
              };
            }
            return {
              data: [],
              total: count,
              success: true,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
            };
          }
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        actionRef={actionRef}
        cardBordered
        columnsState={{
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              setOpenModal(true);
            }}
          >
            签约新企业支付宝账号
          </Button>,
        ]}
      />
      <Modal
        title="签约新企业支付宝账号"
        open={openModal}
        maskClosable={false}
        onCancel={() => {
          setOpenModal(false);
        }}
        okText={success ? '已签约' : '确定'}
        destroyOnClose
        okButtonProps={{
          loading,
        }}
        onOk={async () => {
          if (success) {
            setOpenModal(false);
            setSuccess(false);
            actionRef.current?.reload();
            return;
          }
          await form.validateFields();
          const values = form.getFieldsValue();
          setLoading(true);
          aliPayEnterpriseAuthentication(values)
            .then((res: any) => {
              if (res.success) {
                window.open(res.data);
                setSuccess(true);
              } else {
                message.error(res.resultMessage);
              }
            })
            .finally(() => {
              setLoading(false);
            });
        }}
      >
        <div className="text-[20px] mb-4 text-center mt-4">
          该企业支付宝账号将用于您进行转账交易使用,
          请仔细填写。（只能签约企业支付宝）
        </div>
        <Form form={form}>
          <Form.Item
            label="企业支付宝账号"
            name={'alipayNickName'}
            rules={[{ required: true, message: '请输入企业支付宝账号' }]}
          >
            <Input placeholder="请输入企业支付宝账号" />
          </Form.Item>
          <Form.Item
            label="支付宝主体名称"
            name={'alipayName'}
            rules={[{ required: true, message: '请输入支付宝主体名称' }]}
          >
            <Input placeholder="请输入支付宝主体名称" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ACSPage;
